package com.ailanyin.admin.aspect;

import com.ailanyin.admin.service.SysLogService;
import com.ailanyin.common.service.RedisService;
import com.ailanyin.common.utils.EmptyUtil;
import com.ailanyin.common.utils.IpUtil;
import com.ailanyin.model.SysLog;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * 日志切面
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:43
 */
@Aspect
@Component
@Order(1)
public class AdminLogAspect {

    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private RedisService redisService;

    @Value("${redis.database}")
    private String database;

    private static final String SWITCH_KEY = ":sys:config:sys.log.switch";
    private static final String LEVEL_KEY = ":sys:config:sys.log.level";
    private static final String SWITCH_ON = "on";

    @Pointcut("execution(public * com.ailanyin.admin.controller.*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

        if (getSwitchFlag()) {
            return addLog(joinPoint);
        }
        return joinPoint.proceed();
    }

    /**
     * 查询是否符合级别
     *
     * @param httpMethod get/put/post/delete
     * @return boolean
     */
    private boolean getLevelFlag(String httpMethod) {
        try {
            return redisService.get(database + LEVEL_KEY).toString().contains(httpMethod);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 查询日志是否开启
     *
     * @return boolean
     */
    private boolean getSwitchFlag() {
        try {
            return SWITCH_ON.equals(redisService.get(database + SWITCH_KEY));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 添加进数据库
     *
     * @param joinPoint joinPoint
     * @return obj
     * @throws Throwable Throwable
     */
    private Object addLog(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String httpMethod = request.getMethod();
        Object result = joinPoint.proceed();
        if (getLevelFlag(httpMethod)) {
            SysLog sysLog = new SysLog();
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            if (method.isAnnotationPresent(ApiOperation.class)) {
                ApiOperation log = method.getAnnotation(ApiOperation.class);
                sysLog.setDescription(log.value());
            }
            long endTime = System.currentTimeMillis();
            sysLog.setUsername(request.getRemoteUser());
            sysLog.setIp(IpUtil.getIpAddr(request));
            sysLog.setMethod(httpMethod);
            sysLog.setParameter(JSON.toJSONString(getParameter(method, joinPoint.getArgs())));
            sysLog.setSpendTime((int) (endTime - startTime));
            sysLog.setStartTime(new Date());
            sysLog.setUri(request.getRequestURI());
            sysLogService.insertLog(sysLog);
        }
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>(16);
                String key = parameters[i].getName();
                if (EmptyUtil.isNotEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
